package com.zxl.support;

import com.zxl.annotations.BusinessCode;
import com.zxl.service.KettleXmlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class BusinessAnnotation implements ApplicationListener<ContextRefreshedEvent> {
    private static Map<String, KettleXmlService> businessMap = null;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

        //根据注解获取bean对象
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(BusinessCode.class);
        businessMap = new HashMap<>();
        beansWithAnnotation.forEach((key, value) -> {
            String code = value.getClass().getAnnotation(BusinessCode.class).code();
            boolean active = value.getClass().getAnnotation(BusinessCode.class).active();
            if (active) {
                businessMap.put(code, (KettleXmlService) value);
            }
        });
    }

    public String getXml(String type) {
        if (businessMap != null && businessMap.containsKey(type)) {
          return businessMap.get(type).getXml();
        }
        return "该业务逻辑未启用！";
    }
}